import Vue from 'vue';
import ImageViewer from '@/components/image-viewer/index.vue';
// 创建一个构造函数；
const Img = Vue.extend(ImageViewer);
const pic = Vue.directive('pic', {
  inserted: (el, binding, vnode) => {
    // 给绑定的el添加点击事件
    el.addEventListener('click', (e) => {
      // 创建元素，及组件

      e = e || window.event;
      var e_target = e.target || e.srcElement;

      if (e_target.tagName.toLowerCase() != 'img') {
        return;
      }
      // 删除之前创建的dom
      let container = document.querySelector('.viewer-container');
      if (container) {
        let parentNode = container.parentNode;
        parentNode.removeChild(container);
      }
      const img = new Img({
        el: document.createElement('div')
      });
      e.stopPropagation();
      e.preventDefault();
      var lastImg = [];
      let imgs = el.querySelectorAll('img');
      // 多张图片循环的时候
      imgs = Array.prototype.slice.call(imgs);
      if (imgs.length) {
        imgs.forEach((item) => {
          lastImg.push({
            title: item.title,
            alt: item.title,
            url: item.src.split('?')[0] || item.src
          });
        });
        let _target = e_target.src.split('?')[0] || e_target.src;
        let index = lastImg.findIndex((item) => {
          return item.url === _target;
        });
        var [...lastImgCopy] = lastImg;
        if (index > -1) {
          var _splice = lastImg.splice(index, lastImg.length - index);
          var _leave = lastImgCopy.splice(0, index);
        }
        lastImg = _splice.concat(_leave);
      } else {
        // 单张图片时
        lastImg.push({
          title: e_target.title,
          alt: e_target.title,
          url: e_target.src.split('?')[0] || e_target.src
        });
      }
      img.images = [];
      img.images = lastImg;
    });
  }
});

export default pic;
